<template>
  <div class="login-container">
    <el-card class="login-card" shadow="hover">
      <h3 class="login-title">登录</h3>
      <el-form :model="loginForm" @submit.prevent="handleLogin">
        <el-form-item>
          <el-input v-model="loginForm.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" placeholder="密码" type="password" :show-password="true"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" class="login-button">登录</el-button>
        </el-form-item>
        <div class="form-footer">
          <el-link @click="handleRegister" class="register-link">没有账号？点击注册</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {reactive} from 'vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';
import {useRouter} from 'vue-router';

const router = useRouter();

const loginForm = reactive({
  username: '',
  password: ''
});

const handleLogin = async () => {
  try {
    const response = await axios.post('http://localhost:3000/api/login', loginForm);
    if (response.data.message === 'Login successful') {
      ElMessage.success('登录成功');
      localStorage.setItem('isAuthenticated', 'true');
      await router.push('/home'); // 跳转到主页面
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error('登录失败');
  }
};

const handleRegister = () => {
  router.push('/register'); // 跳转到注册页面
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f2f2f2;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.login-button {
  width: 100%;
}

.form-footer {
  text-align: center;
  margin-top: 10px;
}

.register-link {
  font-size: 14px;
  color: #409EFF;
  cursor: pointer;
}
</style>
